package com.htfyun.factorytest.agingtest;

import android.annotation.SuppressLint;
import android.app.AlarmManager;
import android.app.KeyguardManager;
import android.app.PendingIntent;
import android.bluetooth.BluetoothAdapter;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Message;
import android.os.PowerManager;
import android.text.TextUtils;
import android.view.View;

import com.htfyun.eink.EinkUtils;
import com.htfyun.factorytest.R;
import com.htfyun.factorytest.RootApplication;
import com.htfyun.factorytest.common.Constants;
import com.htfyun.factorytest.common.SettingsUtils;
import com.htfyun.factorytest.common.StandbyUtil;
import com.htfyun.factorytest.utils.DebugLog;
import com.htfyun.factorytest.utils.SystemPropertyUtil;
import com.htfyun.factorytest.utils.TimeStringUtils;

import java.io.File;

public class TestSleep extends AgingTestItemBase {

    private final static String SLEEP_ACTION = "com.rockchip.sleep.ACTION_TEST_CASE_SLEEP";

    private final long AWAKE_TIME = 5000L;

    private long SLEEP_TIME = 20000L;
    public int SCREEN_OFF_TIME = 15000;
//    private int MAX_TIMES = 2;
//    private boolean isReverse = false;
//    private int TEST_TIMES = 0;
//    private static final int MSG_TOGGLE_WIFI = 20;
//    private static final int PERIOD_TOGGLE_WIFI = UsefulUtils.isLowRamDevice() ? 12000 : 8000;
//    private static final int PERIOD_DISABLE_WIFI = UsefulUtils.isLowRamDevice() ? 6000 : 3000;
//    private final WifiManager wm;

    private static final int MSG_UPDATE_UI = 100;
    private static final int PERIOD_UPDATE_UI = 60000;

    //system defined
    private static final int SYS_RTC_WAKEUP = 4;
    private static final int SYS_ELAPSED_REALTIME_WAKEUP = 4;

    public TestSleep(Context context, View view) {
        super(context, view);
//        wm = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);

        String sleepTimeString = SystemPropertyUtil.getSystemProperty("persist.aging.sleep_time");
        if (!TextUtils.isEmpty(sleepTimeString) && TextUtils.isDigitsOnly(sleepTimeString)) {
            SLEEP_TIME = Long.parseLong(sleepTimeString);
        }

        String screenOffTimeString = SystemPropertyUtil.getSystemProperty("persist.aging.screen_off_time");
        if (!TextUtils.isEmpty(screenOffTimeString) && TextUtils.isDigitsOnly(screenOffTimeString)) {
            SCREEN_OFF_TIME = Integer.parseInt(screenOffTimeString);
        }

        WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        if (wifiManager != null && wifiManager.isWifiEnabled()) {
            wifiManager.setWifiEnabled(false);
        }
        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (bluetoothAdapter != null && bluetoothAdapter.isEnabled()) {
            BluetoothAdapter.getDefaultAdapter().disable();
        }
    }

    @Override
    public void handleMessage(Message msg) {
        final int what = msg.what;
//        final boolean isEnabled = msg.arg1 == 1;
        switch (what) {
            case MSG_UPDATE_UI:
                updateUI();
                getHandler().postDelayed(() -> {
                    final File modelFile = new File(Constants.LTE_MODEL_PATH);
                    if (!modelFile.exists()) {
                        DebugLog.e("TestSleep usb error +1, isScreenOn " + isScreenOn);
                        if (isScreenOn) {
                            int count = AgingTestItemAttr.getSleepUSBErrorCount(getContext());
                            AgingTestItemAttr.setSleepUSBErrorCount(getContext(), ++count);
                        }
                    }
                }, 1000 * 12);
                getHandler().sendEmptyMessageDelayed(MSG_UPDATE_UI, PERIOD_UPDATE_UI);
                break;

//            case MSG_TOGGLE_WIFI:
////                toggleWifiEnable();
//                DebugLog.d("TEST_TIMES = " + TEST_TIMES);
//                if (TEST_TIMES >= MAX_TIMES) {
//                    TEST_TIMES = 0;
//                    return;
//                }
//
//                if (isEnabled == wm.isWifiEnabled()) {
//                    DebugLog.d("wifi error +1");
//                    int count = AgingTestItemAttr.getHardwareWifiErrorCount(getContext());
//                    count++;
//                    AgingTestItemAttr.setHardwareWifiErrorCount(getContext(), count);
//                }
//                toggleWifiEnable(isEnabled);
//                TEST_TIMES++;
//                int delay = isEnabled ? PERIOD_TOGGLE_WIFI : PERIOD_DISABLE_WIFI;
//                DebugLog.d("Delay " + delay + "ms to control wifi " + !isEnabled);
//                sendMessageDelay(MSG_TOGGLE_WIFI, !isEnabled, delay);
//                break;
        }
    }

    @Override
    protected void doStartTest() {

        DebugLog.e("TestSleep doStartTest");

        IntentFilter filter = new IntentFilter(SLEEP_ACTION);
        filter.addAction(Intent.ACTION_SCREEN_ON);
        filter.addAction(Intent.ACTION_SCREEN_OFF);
        getContext().registerReceiver(sleepTestReceiver, filter);

        EinkUtils.setWifiAutoOffTimeout(getContext(), 0);
        startTestSleep();
        getHandler().sendEmptyMessage(MSG_UPDATE_UI);
        StandbyUtil.setStandbyPng("休眠测试中");

    }

    /*private void startTestWifi() {

//        getHandler().sendEmptyMessage(MSG_TOGGLE_WIFI);
        DebugLog.d(!isReverse ? "目前是 关开关， 下次是 开关开" : "目前是 开关开， 下次是 关开关");
        toggleWifiEnable(isReverse);
        sendMessageDelay(MSG_TOGGLE_WIFI, !isReverse, PERIOD_TOGGLE_WIFI);
        isReverse = !isReverse;

    }

    private void stopTestWifi() {

        getHandler().removeMessages(MSG_TOGGLE_WIFI);

    }

    private void toggleWifiEnable(boolean enabled) {
        DebugLog.i("toggleWifiEnable() " + enabled);
//        WifiManager wm = (WifiManager) getContext().getSystemService(Context.WIFI_SERVICE);
        if (wm == null) {
            return;
        }

        wm.setWifiEnabled(enabled);

    }

    private void sendMessageDelay(int what, boolean b, int delay) {
        Message m = new Message();
        m.what = what;
        m.arg1 = b ? 1 : 0;
        getHandler().sendMessageDelayed(m, delay);
    }*/

    @Override
    protected void doStopTest() {

        DebugLog.e("TestSleep doStopTest");

        EinkUtils.setWifiAutoOffTimeout(getContext(), 240);
        turnOnScreen();
        stopAlarm();
        getContext().unregisterReceiver(sleepTestReceiver);
        getHandler().removeMessages(MSG_UPDATE_UI);

        SettingsUtils.setScreenOffTimeForFT(getContext());
        StandbyUtil.resetStandbyPng();

        /*if (DeviceAttr.getRunningDeviceAttr().hasWiFi()) {
            stopTestWifi();
        }*/
    }

    @Override
    public AgingTestItemAttr getAgingTestItemAttr() {
        return AgingTestItemAttr.sleep;
    }

    private void startTestSleep() {

        stopAlarm();

        try {
            SettingsUtils.setScreenOffTime(getContext(), SCREEN_OFF_TIME);
//            setAlarm(SLEEP_TIME, true);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @SuppressLint("WrongConstant")
    private void setAlarm(long intervalMillis, boolean repeat) {
        AlarmManager alarmManager = (AlarmManager) getContext()
                .getSystemService(Context.ALARM_SERVICE);

        if (alarmManager == null) {
            return;
        }

        PendingIntent pendingIntent = PendingIntent.getBroadcast(
                getContext(), 0, new Intent(SLEEP_ACTION), 0);

        if (repeat) {
            alarmManager.setRepeating(SYS_RTC_WAKEUP,
                    SCREEN_OFF_TIME + intervalMillis + System.currentTimeMillis(), SCREEN_OFF_TIME + intervalMillis,
                    pendingIntent);
        } else {
            alarmManager.setExact(SYS_RTC_WAKEUP,
                    System.currentTimeMillis() + intervalMillis,
                    pendingIntent);
        }
    }

    private void stopAlarm() {

        PendingIntent localPendingIntent = PendingIntent.getBroadcast(
                getContext(), 0, new Intent(SLEEP_ACTION), 0);
        AlarmManager alarmManager = ((AlarmManager) getContext().getSystemService(Context.ALARM_SERVICE));

        if (alarmManager != null) {
            alarmManager.cancel(localPendingIntent);
        }
    }

    private void updateUI() {
        final int errorCount = AgingTestItemAttr.getSleepUSBErrorCount(getContext());
        final long usedTime = AgingTestItemAttr.getAgingTimeTick_ms(getContext()) - getAgingTestItemAttr().getStartTime_ms(getContext());
        final String timeStr = TimeStringUtils.makeTimeString(usedTime);

        String info = getContext().getString(R.string.aging_sleep_info,
                SCREEN_OFF_TIME / 1000,
                SLEEP_TIME / 1000, getAgingTestItemAttr().getTestCount(getContext()),
                timeStr);
        if (RootApplication.enableUsbCheck) {
            info += getContext().getString(R.string.aging_usb_info, errorCount);
        }
        updateTxtItemInfo(info);

    }

    private boolean isScreenOn = false;
    private BroadcastReceiver sleepTestReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context mContext, Intent intent) {
            final String action = intent.getAction();
            if (action == null) {
                return;
            }
            DebugLog.e("SleepTestReceiver onReceive, action = " + action);

            if (action.equals(SLEEP_ACTION)) {
                int count = getAgingTestItemAttr().getTestCount(getContext());
                count += 1;
                getAgingTestItemAttr().setTestCount(mContext, count);

                updateUI();

                turnOnScreen();

            } else if (action.equals(Intent.ACTION_SCREEN_ON)) {
                isScreenOn = true;
                getHandler().sendEmptyMessage(MSG_UPDATE_UI);

//                startTestWifi();

            } else {
                if (action.equals(Intent.ACTION_SCREEN_OFF)) {
                    isScreenOn = false;
                    setAlarm(SLEEP_TIME, false);
                    getHandler().removeMessages(MSG_UPDATE_UI);

                }
            }

        }

    };

    private void turnOnScreen() {
        PowerManager pw = (PowerManager) getContext().getSystemService(Context.POWER_SERVICE);
        if (pw != null) {
            pw.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.FULL_WAKE_LOCK,
                    "factoryTest:ScreenOnTimer").acquire(AWAKE_TIME);
        }

        KeyguardManager km = (KeyguardManager) getContext().getSystemService(Context.KEYGUARD_SERVICE);
        if (km != null && Build.VERSION.SDK_INT <= Build.VERSION_CODES.O_MR1) {
            km.newKeyguardLock("TestCaseSleep").disableKeyguard();
        }
    }

}
